﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AutoMapper;
using NAccounting.Models;
using System.Data;
using NAccounting.QueryObjects;

namespace NAccounting.Controllers
{
    public class ActivityController : Controller
    {
        private NAccountEntities db = new NAccountEntities();

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Create(int projectId)
        {
            var project = db.Projects.SingleOrDefault(x => x.Id == projectId);

            var activity = new ActivityDetailsModel
            {
                ProjectId = project.Id,
                ProjectName = project.Name,
            };

            return View("Edit", activity);
        }

        [HttpPost]
        public ActionResult Create(ActivityDetailsModel model)
        {
            if (!ModelState.IsValid) return View(model);

            var entity = Mapper.Map<ActivityDetailsModel, ProjectActivity>(model);
            db.ProjectActivities.Attach(entity);
            db.ObjectStateManager.ControlStateByCondition<ProjectActivity>(entity, x => x.Id > 0);

            db.SaveChanges();

            return RedirectToAction("Edit", "Project", new { Id = model.ProjectId });
        }

        public ActionResult Edit(int id)
        {
            var entity = db.ProjectActivities.SingleOrDefault(x => x.Id == id);
            if (entity == null) return HttpNotFound();

            var model = Mapper.Map<ProjectActivity, ActivityDetailsModel>(entity);

            return View(model);
        }

        [HttpPost]
        public ActionResult Edit(ActivityDetailsModel model)
        {
            return Create(model);
        }

        public ActionResult Delete(int id)
        {
            //TODO: Implementar as regras para verificar se é possível excluir uma atividade.
            var entity = db.ProjectActivities.SingleOrDefault(x => x.Id == id);
            var projectId = entity.ProjectId;

            db.ProjectActivities.DeleteObject(entity);
            db.SaveChanges();

            return RedirectToAction("Edit", "Project", new { Id = projectId });
        }

        public JsonResult GetActiveActivities(string sidx, string sord, int page, int rows)
        {
            var queryObject = new ProjectActivityQueryObject(db);
            queryObject.Active = DomainBoolean.Yes();

            var pageIndex = page - 1;
            var pagedResult = queryObject.Get(pageIndex, rows);

            var totalRecords = pagedResult.Total;
            var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);

            var jsonResult = new
            {
                totalPages = totalPages,
                page = page,
                records = totalRecords,
                rows = (
                    from e in pagedResult.List
                    let cellValues = new
                    {
                        Id = e.Id.ToString(),
                        Actions = "",
                        Name = e.Name,
                        Description = e.Description,
                        canEdit = Boolean.TrueString.ToLower(),
                        canStart = (e.CanStart()).ToString().ToLower(),
                        isStarted = (e.IsStarted()).ToString().ToLower()
                    }
                    select new
                    {
                        id = e.Id,
                        cell = new string[]{
                             cellValues.Id, 
                             cellValues.Actions, 
                             cellValues.Name, 
                             cellValues.Description,
                             cellValues.canEdit,
                             cellValues.canStart,
                             cellValues.isStarted
                        }
                    }).ToArray()
            };

            return Json(jsonResult, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Start(int id)
        {
            var activity = db.ProjectActivities.SingleOrDefault(x => x.Id == id);

            if (activity.CanStart())
            {
                activity.Start();
            }

            db.SaveChanges();

            return View("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}

public struct DomainBoolean
{
    public static bool Yes() { return true; }
    public static bool No() { return false; }
}